<template>
  <div class="content">

    <el-form ref="form" :model="form" label-width="120px" size="mini" :inline="true">


      <el-form-item label="请选择用户类型:">
        <el-radio-group v-model="form.userType" @change="changeType">
          <el-radio label="学生"></el-radio>
          <el-radio label="老师"></el-radio>
        </el-radio-group>
      </el-form-item>

      <br/>

      <el-form-item label="">
        <el-input clearable v-model="form.userName" placeholder="请输入学生姓名"></el-input>
      </el-form-item>

      <el-form-item label="">
        <el-input clearable v-model="form.userNo" placeholder="请输入学号"></el-input>
      </el-form-item>

      <el-form-item label="年级：" v-show="showClassStatus">
        <el-select
          clearable
          v-model="form.glassId"
          @change="classList(form.glassId)"
          placeholder="请选择年级"
          size="mini"
          style="width:150px"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in gradeData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级：" v-show="showClassStatus">
        <el-select clearable v-model="form.classId" placeholder="请选择班级" size="mini" style="width:150px">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item,index) in classData"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-button type="primary" size="mini" class="btn" @click="search"><i class="fa fa-search"
                                                                           style="margin-right:5px;"></i>查询
      </el-button>
      <el-button type="primary" size="mini" class="btn" @click="downCommon('/admin/excel/wallet')"><i
        class="fa fa-arrow-down"
        style="margin-right:5px;"></i>往期结转
      </el-button>
      <el-button type="primary" size="mini" class="btn" @click="downCommon('/admin/excel/replenishWallet')"><i
        class="fa fa-arrow-down"
        style="margin-right:5px;"></i>充值未到账
      </el-button>
      <el-button type="primary" size="mini" @click="excelExport"><i class="fa fa-arrow-down" style="margin-right:5px;"></i>导出</el-button>


      <el-upload
        class="upload"
        :action="url+'/admin/wallet/upload'"
        :on-success="uploadSuccess"
        :headers="requestHeader"
        :limit="100"
        accept="xlsx"
        :show-file-list="false"
        :on-exceed="handleExceed"
      >
        <el-button size="mini" type="primary"><i class="fa fa-arrow-up" style="margin-right:5px;"></i>往期余额</el-button>
      </el-upload>


      <el-upload
        class="upload"
        :action="url+'/admin/wallet/replenishUpload'"
        :on-success="uploadSuccess"
        :headers="requestHeader"
        :limit="100"
        accept="xlsx"
        :show-file-list="false"
        :on-exceed="handleExceed"
      >
        <el-button size="mini" type="primary"><i class="fa fa-arrow-up" style="margin-right:5px;"></i>充值未到账</el-button>
      </el-upload>
    </el-form>

    <!-- <el-divider></el-divider> -->
    <!--detail展示页面-->

    <template>
      <el-table
        :data="tableData"
        v-loading="loading"
        size="mini"
        height="470"
        style="width: 100%">
        <!--        <el-table-column type="expand">-->
        <!--          <template slot-scope="props">-->
        <!--            <div class="detail">-->
        <!--              <h3>剩余总额：¥{{props.row.allowance+props.row.balance}}</h3>-->
        <!--              <p>补助钱包余额：¥{{props.row.balance}}</p>-->
        <!--              <p>充值钱包余额：¥{{props.row.allowance}}</p>-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="账户ID" prop="id"></el-table-column>
        <el-table-column label="姓名" prop="userName"></el-table-column>
        <el-table-column label="年级" prop="gradeName"></el-table-column>
        <el-table-column label="班级" prop="className"></el-table-column>
        <el-table-column label="余额" prop="balance"></el-table-column>
        <el-table-column label="冻结金额" prop="frozenBalance"></el-table-column>
        <el-table-column
          label="账户状态"
          prop="status">
          <template slot-scope="scope">
            <span>{{scope.row.status==1?'正常':'冻结'}}</span>
          </template>
        </el-table-column>


        <el-table-column label="是否上传头像" prop="faceUploadFlag"></el-table-column>

        <el-table-column
          label="用户类型"
          prop="userType">
          <template slot-scope="scope">
            <span>{{scope.row.userType==1?'学生':'老师'}}</span>
          </template>
        </el-table-column>

        <el-table-column label="身份证号码" prop="idNo"></el-table-column>


        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"><i class="fa fa-sign-out" aria-hidden="true" style="margin-right:5px;"></i>转出
            </el-button>
            <el-button
              size="mini"
              @click="detail(scope.$index, scope.row)"><i class="fa fa-eye" aria-hidden="true" style="margin-right:5px;"></i>详情
            </el-button>
          </template>
        </el-table-column>

      </el-table>
    </template>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20,50,100]"
      :page-size="everyPageNum"
      layout="total, sizes,prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--新增编辑弹框-->
    <el-dialog title="创建学生信息" :visible.sync="showEdit" width="40%" v-dialogDrag>
      <editStudent @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></editStudent>
    </el-dialog>


    <!--    详情展示弹框-->
    <el-dialog title="" :visible.sync="detailShow" width="85%" height="80%">
      <el-button type="primary" size="mini" @click="excelDetail"><i class="fa fa-arrow-down" style="margin-right:5px;"></i>导出</el-button>
      <el-table :data="detailList">
        <el-table-column property="date" label="业务类型" width="80">
          <template slot-scope="scope">
            <span v-show="scope.row.bizType==1">消费</span>
            <span v-show="scope.row.bizType==2">充值</span>
            <span v-show="scope.row.bizType==3">退款</span>
            <span v-show="scope.row.bizType==4">转出</span>
            <span v-show="scope.row.bizType==5">转入</span>
          </template>
        </el-table-column>
        <el-table-column property="amount" label="金额" width="150"></el-table-column>
        <el-table-column property="balance" label="账户余额" width="150"></el-table-column>
        <el-table-column property="extNumber" label="订单编号" width="200">
          <template slot-scope="scope">
            <span>{{scope.row.extNumber||'- -'}}</span>
          </template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间" width="200"/>
        <el-table-column property="remark" label="备注"></el-table-column>
      </el-table>
      <div style="height: 50px;"></div>
      <el-pagination
        background
        @current-change="handledetail"
        style="transform: translateY(-50px)"
        layout="prev, pager, next"
        :total="detailTotal">
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
  import Cookies from 'js-cookie'
  import editStudent from '@/components/StudentManagement/edit'

  export default {
    name: 'StudentManagement',
    components: {
      editStudent
    },
    data() {
      return {
        detailList: [],
        detailTotal: 0,//分页总页数
        currentDetailId: 0,//点击当前id
        url: this.$Config.url,
        showEdit: false,//显示编辑弹框
        detailShow: false,//详情弹框
        updateStatus: 1,//默认是新增
        loading: false,
        userName: "",
        total: 1,//总页数
        everyPageNum: 10,//每页多少条
        currentPage: 1,//当前页
        requestHeader: {
          'x-baie-admin-token': Cookies.get('token')
        },
        form: {
          userName: '',//姓名
          userNo: '',//学号
          userType: '学生',
          userStatus:'1' ,//账户正常
          gradeId: '',
          classId:''
        },
        tableData: [],
        showClassStatus: true,
        gradeData:[],//年纪列表
        classData:[],//班级列表
      }
    },
    mounted() {
      this.common()
      this.gradeList()
    },
    methods: {
      excelExport() {
        const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
        // if (JSON.parse(localStorage.getItem("userInfo")).deptId) {
        var divFrame = window.parent.document.getElementById(
          "downLoadListFrame"
        );
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame);
        }
        var iframe = window.parent.document.createElement("iframe");
        iframe.setAttribute("id", "downLoadListFrame");
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe);
        divFrame = window.parent.document.getElementById("downLoadListFrame");
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = `${this.url}/admin/wallet/data/exportUser?userType=${this.form.userType=='学生'?1:2}&userNo=${this.form.userNo}&userName=${this.form.userName}&gradeId=${this.form.glassId||''}&classId=${this.form.classId||''}`;
        divFrame.style.display = "none";
        // } else {
        //   this.$message({
        //     message: "超级管理员无法下载模板",
        //     type: "warning"
        //   });
        // }
      },
      excelDetail() {
        const deptId = JSON.parse(localStorage.getItem("userInfo")).deptId;
        // if (JSON.parse(localStorage.getItem("userInfo")).deptId) {
        var divFrame = window.parent.document.getElementById(
          "downLoadListFrame"
        );
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame);
        }
        var iframe = window.parent.document.createElement("iframe");
        iframe.setAttribute("id", "downLoadListFrame");
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe);
        divFrame = window.parent.document.getElementById("downLoadListFrame");
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = `${this.url}/admin/walletflow/export?walletId=${this.currentDetailId}&userName=${this.userName}`;
        divFrame.style.display = "none";
        // } else {
        //   this.$message({
        //     message: "超级管理员无法下载模板",
        //     type: "warning"
        //   });
        // }
      },
      handledetail(val) {
        console.log(val)
        this.detail('', {}, val)
      },
      detail(index, row, currentPage = 0) {
        console.log(index, row)
        const that = this

        if (row.id) {
          that.currentDetailId = row.id
          that.userName = row.userName
        }
        this.$axios
          .get(that.url + '/admin/walletflow/page', {
            params: {
              walletId: that.currentDetailId,
              pageNo: currentPage,
              pageSize: 10
            },
            headers: {
              'x-baie-admin-token': Cookies.get('token')
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.detailList = res.data.data.records
              that.detailTotal = res.data.data.total
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
          })
        this.detailShow = true
      },
      gradeList() {
        const that = this;
        this.$axios
          .get(that.url + "/admin/grade/list", {
            params: {
              deptId: 81
            },
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.gradeData = res.data.data;

              console.log(res.data.data)
            } else {
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      classList(id) {
        const that = this;
        that.form.classId = "";
        this.$axios
          .get(that.url + "/admin/class/list", {
            params: {
              gradeId: id
            },
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          })
          .then(function(res) {
            if (res.data.code == 200) {
              that.classData = res.data.data;
            } else {
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          })
          .catch(function(error) {
            console.log(error);
          });
      },
      handleEdit(index, row) {
        const that = this
        this.$prompt('请输入身份证号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
          inputErrorMessage: '身份证输入不正确'
        }).then(({ value }) => {
          const resultData = {
            id: row.id,
            idNo: value
          }

          that.$axios
            .post(
              that.url + '/admin/wallet/trans',
              that.$qs.stringify(resultData),
              {
                headers: {
                  'x-baie-admin-token': Cookies.get('token')
                }
              }
            )
            .then(function(res) {
              if (res.data.code == '200') {
                that.$message({
                  message: '转出成功',
                  type: 'success'
                })

                that.common(that.currentPage, that.everyPageNum)//刷新列表
              } else {
                that.$message({
                  message: res.data.msg,
                  type: 'warning'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
            })
        }).catch(() => {
          console.log('已取消')
        })
      },
      uploadSuccess(response, file, fileList) {
        if (response.code == 200) {
          this.$message({
            message: '导入成功',
            type: 'success'
          })
          this.common(this.currentPage, this.everyPageNum)
        } else {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        }
      },

      downCommon(url) {
        var divFrame = window.parent.document.getElementById(
          'downLoadListFrame'
        )
        //判断是否存在，如果存在先移除，再重新创建
        if (divFrame != null) {
          window.parent.document.body.removeChild(divFrame)
        }
        var iframe = window.parent.document.createElement('iframe')
        iframe.setAttribute('id', 'downLoadListFrame')
        //download_file.id = "downFrame";
        window.parent.document.body.appendChild(iframe)
        divFrame = window.parent.document.getElementById('downLoadListFrame')
        //隐式调用，（注意：window.parent.document 适应对于，farme内部代码，调用frame 外部dom；如果项目未用frame，改写成 document即可）
        divFrame.src = this.url + url
        divFrame.style.display = 'none'
      },
      changeType() {
        let userType = this.form.userType == '学生' ? 1 : 2
        if(userType == 2){
          this.showClassStatus = false
        }else{
          this.showClassStatus = true
        }
        this.common(this.currentPage, this.everyPageNum, userType)
      },
      handleSizeChange(val) {
        //   每页多少条
        this.everyPageNum = val
        this.common(this.currentPage, val)
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.common(val, this.everyPageNum)
      },
      hideEditStatus(status) {
        this.showEdit = false
        this.common(this.currentPage, this.everyPageNum)
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${
            files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        )
      },
      common(pageNo = 1, pageSize = 10, userType = 1) {
        const that = this
        that.loading = true
        userType = that.form.userType == '学生' ? 1 : 2
        let gradeId = that.form.glassId
        let classId = that.form.classId
        if(userType == 2){
          gradeId = ''
          classId = ''
        }
        this.$axios.get(that.url + '/admin/wallet/page', {
          params: {
            pageNo,
            pageSize,
            userType: userType,
            userName: that.form.userName,
            userNo: that.form.userNo,
            userStatus: that.form.userStatus,
            gradeId: gradeId,
            classId: classId
          },
          headers: {
            'x-baie-admin-token': Cookies.get('token')
          }
        })
          .then(function(res) {
            that.loading = false
            if (res.data.code == 200) {
              that.tableData = res.data.data.records
              that.total = res.data.data.total
            } else {
              that.$message({
                message: res.data.msg,
                type: 'warning'
              })
            }

          })
          .catch(function(error) {
            that.loading = false
            console.log(error)
          })

      },
      handleClick(row) {
        console.log(row)
      },
      search() {
        this.common(this.currentPage, this.everyPageNum)
      }
    }
  }
</script>

<style scoped lang="scss">
  .detail {
    text-align: left;
  }

  .el-select, .el-input {
    width: 150px;
  }

  .el-range-editor--mini.el-input__inner {
    margin-top: 7px;
    margin-right: 10px;
    width: 300px;
  }

  .el-pagination {
    float: right;
    margin: 20px 10px;
  }

  .button_list {
    margin-bottom: 10px;
  }

  .content {
    text-align: left;
  }

  .el-divider {
    margin: 10px 0;
  }

  .btn {
    margin-top: 1px;
  }

  .el-form-item {
    margin-bottom: 0;
  }

  .upload {
    display: inline-block;
  }
</style>
